/*******************************************************************************
 * Copyright (c) 2002 Boris Pruessmann and others. All rights reserved. This
 * program and the accompanying materials are made available under the terms of
 * the Common Public License v0.5 which accompanies this distribution, and is
 * available at http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors: Boris Pruessmann - Initial implementation.
 ******************************************************************************/
package net.sourceforge.perforce.ui.action;

import com.google.common.collect.Lists;

import net.sourceforge.perforce.core.resources.IP4File;

import org.eclipse.core.runtime.IAdaptable;

import java.util.Iterator;
import java.util.List;

/**
 * @version $Revision: 488 $
 * @author <a href="mailto:bpruessmann@users.sourceforge.net">Boris
 *         Pruessmann</a>
 */
abstract class P4FileAction extends PerforceAction {
  //----------------------------------------------------------------------------
  // --------- Methods

  /**
   * Called to retrieve an array of selected changelists.
   * 
   * @return array of selected changelists.
   */
  IP4File[] getSelectedPerforceFiles() {
    List<IP4File> resources = null;
    if (!getSelection().isEmpty()) {
      resources = Lists.newArrayList();
      for (Iterator<?> elements = getSelection().iterator(); elements.hasNext();) {
        Object next = elements.next();
        if (next instanceof IP4File) {
          resources.add((IP4File) next);
          continue;
        } else if (next instanceof IAdaptable) {
          Object adapter = ((IAdaptable) next).getAdapter(IP4File.class);
          if (adapter instanceof IP4File) {
            resources.add((IP4File) adapter);
            continue;
          }
        }
      }
    }

    if (resources != null && !resources.isEmpty()) {
      return resources.toArray(new IP4File[resources.size()]);
    }

    return new IP4File[0];
  }
}
